/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.Js;
import com.jeeplus.modules.fee.entity.RecivedDetil;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 装卸收支明细Controller
 * @author 李超辉
 * @version 2018-09-28
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/loadDetil")
public class LoadDetilController extends BaseController {

	@Autowired
	private LoadDetilService loadDetilService;
	@Autowired
	private PositionService positionService;
	@Autowired
	private LoadingIncomeService loadingIncomeService;
	@Autowired
	private LoadingOutService loadingOutService;
	@Autowired
	private LoadingBottomService loadingBottomService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private SlService slService;
	@Autowired
	private LoadjsDetilService loadjsDetilService;
	@Autowired
	private LoadJsService loadJsService;
	
	@ModelAttribute
	public LoadDetil get(@RequestParam(required=false) String id) {
		LoadDetil entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = loadDetilService.get(id);
		}
		if (entity == null){
			entity = new LoadDetil();
		}
		return entity;
	}
	@RequestMapping(value = "cx")
	@ResponseBody
	public String cx(String min,String max,String pro){
		DecimalFormat df = new DecimalFormat("0.00%");
		NumberFormat nf = NumberFormat.getInstance();
		LoadDetil r=new LoadDetil();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			r.setPro(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				r.setPro(UserUtils.getUseroffice());
			}
		}
		r.setMin(min);
		r.setQr(1);
		r.setMax(max);
		List<LoadDetil> list=loadDetilService.findList(r);
		double zsr=0.0;
		double zzc=0.0;
		double zfk=0.0;
		String ids="";
		for(LoadDetil  re:list){
			zsr+=Double.parseDouble(re.getZsr());
			zzc+=Double.parseDouble(re.getZc());
			zfk+=Double.parseDouble(re.getFk());
			ids+=re.getId()+",";
		}
		double mlr=zsr-zzc;
		double lrl=mlr/zsr;
		r.setMax(ids);
		r.setFk(nf.format(zfk).replaceAll(",",""));
		r.setSr(nf.format(zsr).replaceAll(",",""));
		r.setZc(nf.format(zzc).replaceAll(",",""));
		r.setMlr(nf.format(mlr).replaceAll(",",""));
		r.setLrl(df.format(lrl));
		list.add(r);
		Gson g=new Gson();
		return g.toJson(list).toString() ;
	}
	/**
	 * 装卸收支明细列表页面
	 */
	@RequiresPermissions("infor:loadDetil:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/loadDetilList";
	}
	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/infor/4/loadDetilList";
	}

	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = "list2")
	public String list2() {
		return "modules/infor/5/loadDetilList";
	}
	
		/**
	 * 装卸收支明细列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadDetil:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(LoadDetil loadDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			loadDetil.setPro(pro);
		}
			Page<LoadDetil> page = loadDetilService.findPage(new Page<LoadDetil>(request, response), loadDetil);
		return getBootstrapData(page);
	}
	/**
	 * 付款
	 */
	@ResponseBody
	@RequestMapping(value = "fk")
	public String fk(LoadDetil rentDetil,String je, RedirectAttributes redirectAttributes) {
		NumberFormat nf = NumberFormat.getInstance();
		double fkje=Double.parseDouble(je);
		double yfje=Double.parseDouble(rentDetil.getYfje());
		double wfje=Double.parseDouble(rentDetil.getWfje());
		rentDetil.setYfje(nf.format(yfje+fkje).replaceAll(",",""));
		rentDetil.setWfje(nf.format(wfje-fkje).replaceAll(",",""));
		loadDetilService.save(rentDetil);

		return "";
	}
	/**
	 * 装卸收支明细列表数据(报表)
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadDetil:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(LoadDetil loadDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			loadDetil.setPro(pro);
		}
		loadDetil.setQr(1);
		Page<LoadDetil> page = loadDetilService.findPage(new Page<LoadDetil>(request, response), loadDetil);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑装卸收支明细表单页面
	 */
	@RequiresPermissions(value={"infor:loadDetil:view","infor:loadDetil:add","infor:loadDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LoadDetil loadDetil, Model model) {
		if(loadDetil.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				loadDetil.setPro(pro);
				loadDetil.setStatus("已创建");
			}
		}
		model.addAttribute("loadDetil", loadDetil);
		return "modules/infor/loadDetilForm";
	}

	@ResponseBody
	@RequestMapping(value = "getdetil")
	public  String getdetil(String i){
		LoadjsDetil l=new LoadjsDetil();
		l.setPid(i);
		List<LoadjsDetil> list=loadjsDetilService.findList(l);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}
	/**
	 * 取消核销
	 */
	@ResponseBody
	@RequestMapping(value = "qdqx")
	public String qdqx(String idd, RedirectAttributes redirectAttributes) {
		String[] ids=idd.split(",");
		for(String i:ids){
			LoadjsDetil recivedDetil=loadjsDetilService.get(i);
			NumberFormat nf = NumberFormat.getInstance();
			LoadJs js=loadJsService.get(recivedDetil.getPid());
			Double d=Double.parseDouble(recivedDetil.getMoney());
			Double e=Double.parseDouble(js.getHx().replace(",",""));
			Double f=Double.parseDouble(js.getWhx().replace(",",""));
			js.setHx(nf.format(e-d).replaceAll(",",""));
			js.setWhx(nf.format(f+d).replaceAll(",",""));
			if(js.getWhx().equals("0.0")||js.getWhx().equals("0")){
				js.setStatus("已核销");
			}else if(js.getHx().equals("0")||js.getHx().equals("0.0")){
				js.setStatus("已创建");
			}else{

				js.setStatus("部分核销");
			}
			loadJsService.save(js);
			loadjsDetilService.delete(recivedDetil);}
		return "";
	}
	/**
	 * 确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(LoadDetil loadDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		DecimalFormat df = new DecimalFormat("0.00%");
		NumberFormat nf = NumberFormat.getInstance();
		loadDetil.setStatus("已确认");
		loadDetil.setQr(1);
		Sl sl=slService.findUniqueByProperty("pro",loadDetil.getPro());
        sl=slService.get(sl.getId());
        double sj=Double.parseDouble(loadDetil.getZsr())*Double.parseDouble(sl.getSl());
		double mlr=Double.parseDouble(loadDetil.getZsr())-Double.parseDouble(loadDetil.getZc())-sj;
		double lrl=mlr/Double.parseDouble(loadDetil.getZsr());
		loadDetil.setSj(nf.format(sj).replaceAll(",",""));
		loadDetil.setMlr(nf.format(mlr).replaceAll(",",""));
		loadDetil.setLrl(df.format(lrl));
		loadDetilService.save(loadDetil);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 取消确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qxqr")
	public AjaxJson qxqr(LoadDetil loadDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		loadDetil.setStatus("已创建");
		loadDetil.setQr(0);
		loadDetil.setMlr("");
		loadDetil.setLrl("");
		loadDetilService.save(loadDetil);
		j.setMsg("取消确认成功");
		return j;
	}

	/**
	 * 手动计算上月数据
	 */
	@ResponseBody
	@RequestMapping(value = "sd")
	public AjaxJson sd() {
		AjaxJson j = new AjaxJson();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date d=new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, -1);
		d=c.getTime();
		LoadDetil rent=new LoadDetil();
		rent.setDate(d);
		rent.setPro(UserUtils.getUseroffice());
		List<LoadDetil> lo=loadDetilService.findList(rent);
		if(lo!=null&lo.size()>0){
			j.setMsg("请勿重复计算");
			j.setSuccess(false);
			return j;
		}
		LoadingIncome income=new LoadingIncome();
		income.setPro(UserUtils.getUseroffice());
//		List<LoadingIncome> ins=loadingIncomeService.findList(income);
//		if(ins==null||ins.size()<1){
//			j.setMsg("收入单价未维护");
//			j.setSuccess(false);
//			return j;
//		}

		String sql="SELECT p.work_type as type, p.code as code,p.work_type as type, SUM(p.amount) as amount FROM wms_pickdetailed p  where DATE_FORMAT('"+format.format(d)+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m') and p.project_name='"+UserUtils.getUseroffice()+"' GROUP BY p.work_type, p.project_name, p.`code`";
		String sq="SELECT p.work_type as type, p.material_coding as code,SUM(p.quantities_received) as amount FROM wms_receivings_notes p  where DATE_FORMAT('"+format.format(d)+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')and p.project_name='"+UserUtils.getUseroffice()+"' GROUP BY p.work_type,p.project_name, p.material_coding";
		System.out.print("+++++++++++++++++++++++++++++++++++++++++"+sql);
		System.out.print("-------------------------------------------"+sq);
		List<Map<String,Object>> rkmx=jdbc.queryForList(sq);
		List<Map<String,Object>> ckmx=jdbc.queryForList(sql);
		Double ckzl=0.0;
		Double rkzl=0.0;
		double cksr=0.0;
		double rksr=0.0;
		double ckhs=0.0;
		double rkhs=0.0;
		for(Map<String,Object> m:rkmx){
			Goods g=new Goods();
			g.setProject(UserUtils.getUseroffice());
			g.setCode(m.get("code")+"");
			g=goodsService.findList(g).get(0);
			g=goodsService.get(g.getId());
            income.setType(m.get("type")+"");
			income.setMax(d);
			income.setMin(d);
			List<LoadingIncome> ins=loadingIncomeService.findList(income);
			if(ins==null||ins.size()<1){
				j.setMsg(m.get("type")+"收入单价未维护");
				j.setSuccess(false);
				return j;
			}
			income=ins.get(0);
			double zl=Double.parseDouble(g.getGrossWeight())*Double.parseDouble(m.get("amount")+"");
			double sr=(Double.parseDouble(income.getPu())+Double.parseDouble(income.getRad()))*zl;
			rksr+=sr;
			rkhs+=sr*(1+Double.parseDouble(income.getSl()));
			rkzl+=zl;
		}
		for(Map<String,Object> ma:ckmx){
			Goods g=new Goods();
			g.setProject(UserUtils.getUseroffice());
			g.setCode(ma.get("code")+"");
			g=goodsService.findList(g).get(0);
			g=goodsService.get(g.getId());
			income.setType(ma.get("type")+"");
			income.setMax(d);
			income.setMin(d);
			List<LoadingIncome> ins=loadingIncomeService.findList(income);
			if(ins==null||ins.size()<1){
				j.setMsg(ma.get("type")+"收入单价未维护");
				j.setSuccess(false);
				return j;
			}
			income=ins.get(0);
			double zl=Double.parseDouble(g.getGrossWeight())*Double.parseDouble(ma.get("amount")+"");
			double sr=(Double.parseDouble(income.getOu())+Double.parseDouble(income.getAd()))*zl;
			cksr+=sr;
			ckhs+=sr*(1+Double.parseDouble(income.getSl()));
			ckzl+=zl;

		}
          rent.setRk(nf.format(rkzl).replaceAll(",",""));
		  rent.setCk(nf.format(ckzl).replaceAll(",",""));
		  rent.setStatus("已创建");
          double bhs=cksr+rksr;
          double hs=rkhs+ckhs;
          rent.setFjsr("0");
          rent.setZsr(nf.format(hs).replaceAll(",",""));
          rent.setSr(nf.format(bhs).replaceAll(",",""));
		  rent.setSrhs(nf.format(hs).replaceAll(",",""));


//装卸支出
			List<Map<String,Object>> maps=ck(format.format(d),UserUtils.getUseroffice());
			List<Map<String,Object>> map=rk(format.format(d),UserUtils.getUseroffice());
			double zxzc=0.0;
			double zxsr=0.0;
			double ck=0.0;
			double rk=0.0;
			double sr=0.0;
			double bd=0.0;
			double dw=0.0;
			String pp="";
			for(Map<String,Object>m:maps){
				String ppp=m.get("pro")+"-"+positionService.get(m.get("position")+"").getName();
				if(!pp.contains(ppp)){
					pp+=ppp+",";
				LoadingBottom l=new LoadingBottom();
				l.setPosition(positionService.get(m.get("position")+"").getName());
				l.setPro(m.get("pro")+"");
				l.setMax(d);
				l.setMin(d);
				List<LoadingBottom> li=loadingBottomService.findList(l);
					if(li.size()>0&&li!=null){
						bd+=Double.parseDouble(li.get(0).getPrice());
						zxzc+=Double.parseDouble(li.get(0).getPrice());
					}
				}

				List<LoadingOut> outs;
				Double dg=Double.parseDouble(m.get("dg")+"");
				if(dg>0.0){
				outs=getLoadingOut("吨罐",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*dg;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dg;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double dx=Double.parseDouble(m.get("dx")+"");
				if(dx>0.0){
					outs=getLoadingOut("吨箱",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*dx;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dx;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double xht=Double.parseDouble(m.get("xht")+"");
				if(xht>0.0){
					outs=getLoadingOut("小黄桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*xht;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* xht;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double xx=Double.parseDouble(m.get("xx")+"");
				if(xx>0.0){
					outs=getLoadingOut("小箱",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*xx;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* xx;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double xt=Double.parseDouble(m.get("xt")+"");
				if(xt>0.0){
					outs=getLoadingOut("小桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*xt;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* xt;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double zt=Double.parseDouble(m.get("zt")+"");
				if(zt>0.0){
					outs=getLoadingOut("中桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*zt;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* zt;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double dt=Double.parseDouble(m.get("dt")+"");
				if(dt>0.0){
					outs=getLoadingOut("大桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*dt;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dt;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double dai=Double.parseDouble(m.get("dai")+"");
				if(dai>0.0){
					outs=getLoadingOut("袋",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*dai;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dai;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double jian=Double.parseDouble(m.get("jian")+"");
				if(jian>0.0){
					outs=getLoadingOut("件",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","出库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*jian;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* jian;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
			}

			for(Map<String,Object>m:map){

				String ppp=m.get("pro")+"-"+positionService.get(m.get("position")+"").getName();
				if(!pp.contains(ppp)){
					pp+=ppp+",";

				LoadingBottom l=new LoadingBottom();
				l.setPosition(positionService.get(m.get("position")+"").getName());
				l.setPro(m.get("pro")+"");
				l.setMax(d);
				l.setMin(d);
				List<LoadingBottom> li=loadingBottomService.findList(l);
				if(li.size()>0&&li!=null){
					bd+=Double.parseDouble(li.get(0).getPrice());
					zxzc+=Double.parseDouble(li.get(0).getPrice());
				}
				}
				List<LoadingOut> outs;
				Double dg=Double.parseDouble(m.get("dg")+"");
				if(dg>0.0){
					outs=getLoadingOut("吨罐",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*dg;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dg;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double dx=Double.parseDouble(m.get("dx")+"");
				if(dx>0.0){
					outs=getLoadingOut("吨箱",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*dx;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dx;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double xht=Double.parseDouble(m.get("xht")+"");
				if(xht>0.0){
					outs=getLoadingOut("小黄桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						ck+=Double.parseDouble(outs.get(0).getPrice())*xht;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* xht;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double xx=Double.parseDouble(m.get("xx")+"");
				if(xx>0.0){
					outs=getLoadingOut("小箱",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*xx;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* xx;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double xt=Double.parseDouble(m.get("xt")+"");
				if(xt>0.0){
					outs=getLoadingOut("小桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*xt;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* xt;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double zt=Double.parseDouble(m.get("zt")+"");
				if(zt>0.0){
					outs=getLoadingOut("中桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*zt;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* zt;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double dt=Double.parseDouble(m.get("dt")+"");
				if(dt>0.0){
					outs=getLoadingOut("大桶",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*dt;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dt;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double dai=Double.parseDouble(m.get("dai")+"");
				if(dai>0.0){
					outs=getLoadingOut("袋",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*dai;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* dai;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
				Double jian=Double.parseDouble(m.get("jian")+"");
				if(jian>0.0){
					outs=getLoadingOut("件",positionService.get(m.get("position")+"").getName(),m.get("pro")+"","入库",d);
					if(outs!=null&&outs.size()>0){
						rk+=Double.parseDouble(outs.get(0).getPrice())*jian;
						zxzc+=Double.parseDouble(outs.get(0).getPrice())* jian;
					}else{
						j.setSuccess(false);
						j.setMsg("支出价格未维护");
						return j;
					}
				}
			}
			rent.setBd(nf.format(bd).replaceAll(",",""));
		rent.setRkzc(nf.format(rk).replaceAll(",",""));
		rent.setCkzc(nf.format(ck).replaceAll(",",""));
		rent.setZc(nf.format(zxzc).replaceAll(",",""));
		rent.setYfje("0");
		rent.setWfje(nf.format(zxzc).replaceAll(",",""));
		rent.setFjzc("0");
		rent.setFk("0");
			loadDetilService.save(rent);


		j.setMsg("计算成功");
		return j;
	}

	public List<Map<String,Object>> rk(String min,String pro){
		String sql;

		if(!pro.equals("总部")){
			sql = "SELECT p.pro AS pro,p.position AS position,p.NAME AS NAME,p.type AS type, SUM( p.dg) AS dg,SUM(p.dx) as dx,SUM(p.xht) as xht,SUM( p.xx) AS xx,SUM(p.xt) as xt,SUM(p.zt) as zt,SUM(p.dt) as dt,SUM(p.dai) as dai,SUM(p.jian) as jian FROM `wms_statistics` p WHERE   DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')  and p.pro='" + pro + "'   GROUP BY p.pro,p.name, p.position";
		}else{
			sql = "SELECT p.pro AS pro,p.position AS position,p.NAME AS NAME,p.type AS type, SUM( p.dg) AS dg,SUM(p.dx) as dx,SUM(p.xht) as xht,SUM( p.xx) AS xx,SUM(p.xt) as xt,SUM(p.zt) as zt,SUM(p.dt) as dt,SUM(p.dai) as dai,SUM(p.jian) as jian FROM `wms_statistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')  GROUP BY p.name,p.position ";
		}
		System.out.print(sql);
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		return  list;
	}
	public List<Map<String,Object>> ck(String min,String pro){
		String sq;
		if(!pro.equals("总部")){
			sq = "SELECT p.pro AS pro,p.position AS position,p.NAME AS NAME,p.type AS type, SUM( p.dg) AS dg,SUM(p.dx) as dx,SUM(p.xht) as xht,SUM( p.xx) AS xx,SUM(p.xt) as xt,SUM(p.zt) as zt,SUM(p.dt) as dt,SUM(p.dai) as dai,SUM(p.jian) as jian FROM `wms_outstatistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m') and p.pro='" + pro + "'   GROUP BY  p.pro,p.name, p.position";
		}else{
			sq = "SELECT p.pro AS pro,p.position AS position,p.NAME AS NAME,p.type AS type, SUM( p.dg) AS dg,SUM(p.dx) as dx,SUM(p.xht) as xht,SUM( p.xx) AS xx,SUM(p.xt) as xt,SUM(p.zt) as zt,SUM(p.dt) as dt,SUM(p.dai) as dai,SUM(p.jian) as jian FROM `wms_outstatistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m'))  GROUP BY p.name,p.p.position";
		}
		System.out.print(sq);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		return  lis;
	}

	public  List<LoadingOut> getLoadingOut(String gtype,String position,String pro,String type,Date d){
		LoadingOut loadingOut=new LoadingOut();
		loadingOut.setGtype(gtype);
		loadingOut.setPosition(position);
		loadingOut.setPro(pro);
		loadingOut.setType(type);
		loadingOut.setMin(d);
		loadingOut.setMax(d);
		List<LoadingOut> outs=loadingOutService.findList(loadingOut);
		return outs;
	}
	/**
	 * 保存装卸收支明细
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:loadDetil:add","infor:loadDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(LoadDetil loadDetil, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, loadDetil)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(loadDetil.getIsNewRecord()){
			loadDetil.setFjzc("0");
			loadDetil.setFjsr("0");
			loadDetil.setFk("0");
			loadDetil.setZsr(loadDetil.getSrhs());
			loadDetil.setYfje("0");
			loadDetil.setWfje(loadDetil.getZc());
		}
		loadDetilService.save(loadDetil);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存装卸收支明细成功");
		return j;
	}
	
	/**
	 * 删除装卸收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadDetil:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(LoadDetil loadDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		loadDetilService.delete(loadDetil);
		j.setMsg("删除装卸收支明细成功");
		return j;
	}
	
	/**
	 * 批量删除装卸收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadDetil:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			loadDetilService.delete(loadDetilService.get(id));
		}
		j.setMsg("删除装卸收支明细成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:loadDetil:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(LoadDetil loadDetil, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "装卸收支明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LoadDetil> page = loadDetilService.findPage(new Page<LoadDetil>(request, response, -1), loadDetil);
    		new ExportExcel("装卸收支明细", LoadDetil.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出装卸收支明细记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:loadDetil:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LoadDetil> list = ei.getDataList(LoadDetil.class);
			for (LoadDetil loadDetil : list){
				try{
					loadDetilService.save(loadDetil);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条装卸收支明细记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条装卸收支明细记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入装卸收支明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/loadDetil/?repage";
    }
	
	/**
	 * 下载导入装卸收支明细数据模板
	 */
	@RequiresPermissions("infor:loadDetil:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "装卸收支明细数据导入模板.xlsx";
    		List<LoadDetil> list = Lists.newArrayList(); 
    		new ExportExcel("装卸收支明细数据", LoadDetil.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/loadDetil/?repage";
    }

}